package com.jplus.utill;

import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.util.Arrays;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 发送邮件工具类
 * 
 * @author yuanqy
 */
public class EMailUtil {

	private String fromMail = "";
	private String fromPass = "";
	private String hostName = "";
	private Logger log = LoggerFactory.getLogger(getClass());

	/**
	 * @param fromMail 账号
	 * @param fromPass 密码
	 * @param hostName host[比如：qq,163,aliyun....]
	 */
	public EMailUtil(String fromMail, String fromPass, String hostName) {
		this.fromMail = fromMail;
		this.fromPass = fromPass;
		this.hostName = hostName;
	}

	/**
	 * 发送邮件
	 * 
	 * @param emails 发送到
	 * @param copyto 抄送到
	 * @param title	标题
	 * @param content 内容
	 * @param nickName 发送者名称
	 */
	public boolean sendMail(String[] emails, String[] copyto, String title, String content, String nickName) {
		boolean result = false;
		try {
			Properties props = new Properties();
			props.put("mail.smtp.host", "smtp." + hostName + ".com");
			props.put("mail.smtp.auth", "true");
			Session session = Session.getInstance(props);
			Message msg = createMsg(session, emails, copyto, title, content, nickName);

			Transport transport = session.getTransport("smtp");
			transport.connect("smtp." + hostName + ".com", fromMail, fromPass);
			log.info("[发送邮件]to=" + Arrays.toString(emails) + ";title=" + title);
			
			// -- Create a new message --
			transport.sendMessage(msg, msg.getAllRecipients());
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
			result = false;
		}
		log.info("[发送邮件-完毕]结果：" + result);
		return result;
	}

	/**
	 * 发送邮件[基于SSL]
	 * 
	 * @param emails 发送到
	 * @param copyto 抄送到
	 * @param title	标题
	 * @param content 内容
	 * @param nickName 发送者名称
	 * @return
	 */
	@SuppressWarnings("restriction")
	public boolean sendMailSSL(String[] emails, String[] copyto, String title, String content, String nickName) {
		boolean result = false;
		try {
			Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
			final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
			Properties props = System.getProperties();
			props.setProperty("mail.smtp.host", "smtp." + hostName + ".com");
			props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
			props.setProperty("mail.smtp.socketFactory.fallback", "false");
			props.setProperty("mail.smtp.port", "465");
			props.setProperty("mail.smtp.socketFactory.port", "465");
			props.put("mail.smtp.auth", "true");
			Session session = Session.getDefaultInstance(props, new Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(fromMail, fromPass);
				}
			});
			// session.setDebug(true);
			// -- Create a new message --
			Message msg = createMsg(session, emails, copyto, title, content, nickName);
			log.info("[发送邮件]to=" + Arrays.toString(emails) + ";title=" + title);
			Transport.send(msg);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
			result = false;
		}
		log.info("[发送邮件-完毕]结果：" + result);
		return result;
	}

	private Message createMsg(Session mailSession, String[] emails, String[] copyto, String title, String content, String nickName)
			throws UnsupportedEncodingException, MessagingException {
		MimeMessage message = new MimeMessage(mailSession);
		InternetAddress from = new InternetAddress(javax.mail.internet.MimeUtility.encodeText(nickName) + "<" + fromMail + ">");
		message.setFrom(from);
		InternetAddress[] sendTo = new InternetAddress[emails.length];
		for (int i = 0; i < emails.length; i++)
			sendTo[i] = new InternetAddress(emails[i]);
		InternetAddress[] sendCC = new InternetAddress[copyto.length];
		for (int i = 0; i < copyto.length; i++)
			sendCC[i] = new InternetAddress(copyto[i]);
		message.setRecipients(javax.mail.internet.MimeMessage.RecipientType.TO, sendTo);
		message.setRecipients(javax.mail.internet.MimeMessage.RecipientType.CC, sendCC);
		message.setSubject(title);
		Multipart mp = new MimeMultipart();
		BodyPart html = new MimeBodyPart();
		html.setContent(content, "text/html; charset=utf-8");// html内容
		// html.setText(content);//文本内容
		mp.addBodyPart(html);
		message.setContent(mp, "text/html; charset=utf-8");
		message.setSentDate(new Date());
		message.saveChanges();
		return message;
	}
	
	public static void main(String[] args) {
		EMailUtil email = new EMailUtil("xxxxx@qq.com", "xxxx", "qq");
		email.sendMailSSL(new String[] { "xxxxx@xx.com" }, new String[] {}, "测试标题", "测试内容", "测试名称");
	}
}